package cn.kgc.junketing.provider.service.impl;

import cn.kgc.junketing.provider.entity.User;
import cn.kgc.junketing.provider.exception.GlobalException;
import cn.kgc.junketing.provider.mapper.UserMapper;
import cn.kgc.junketing.provider.service.UserService;
import cn.kgc.junketing.provider.utli.MD5Utils;
import cn.kgc.junketing.provider.utli.UUIDUtils;
import cn.kgc.junketing.provider.vo.ResponseBean;
import cn.kgc.junketing.provider.vo.ResponseBeanEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public ResponseBean findLoginUser(User user) {
        //  进行二次加密
        String md5Second = MD5Utils.md5Second(user.getPwd(), "s1a2l3t4");
        user.setPwd(md5Second);
        //  密码判断
        if (!md5Second.equals(user.getPwd())) throw new GlobalException(ResponseBeanEnum.LOGINERROR);
        User sqlUser = this.userMapper.selectOne(new QueryWrapper<User>().lambda()
                .eq((user.getTel() != null & !Objects.equals(user.getTel(), "")), User::getTel, user.getTel())
                .eq((user.getPwd() != null & !Objects.equals(user.getPwd(), "")), User::getPwd, user.getPwd())
        );
        if (sqlUser == null) throw new GlobalException(ResponseBeanEnum.LOGINERROR);
        //  生产uuid
        String uuid = UUIDUtils.generateUUID();
        //  存入redis
        this.redisTemplate.opsForValue().set("user:" + uuid, sqlUser.getPwd(), 30, TimeUnit.MINUTES);
        return ResponseBean.success(ResponseBeanEnum.SUCCESS, uuid);
    }

    @Override
    public User findUserByTicket(String ticket) {
        return (User) this.redisTemplate.opsForValue().get("user:" + ticket);
    }

}